package com.futvan.z.framework.core;

import com.alibaba.fastjson.JSONObject;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.system.zmessages.z_messages;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;

/**
 * 消息处理类
 */
public class NettyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    /**
     * 消息处理
     * @param fromc_context
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead0(ChannelHandlerContext fromc_context, TextWebSocketFrame msg) throws Exception {
        Result getMsgResult = TextWebSocketFrameToZMessage(msg);
        if(getMsgResult.ifSuccess()){
            z_messages messages = (z_messages) getMsgResult.getData();

        }else{
            z_messages result_msg = new z_messages();
            result_msg.setCommand_type("system_error");//系统错误
            result_msg.setMsgtype("0");//文本
            result_msg.setMsg(getMsgResult.getMsg());//错误信息
            SendMessages(fromc_context,result_msg);
        }

    }

    private void SendMessages(ChannelHandlerContext ctx, z_messages msg) {
        if(z.isNotNull(ctx) && z.isNotNull(ctx.channel()) && ctx.channel().isOpen()){
            if(z.isNotNull(msg) && z.isNotNull(msg.getTouserid())){
                String json = JsonUtil.getJson(msg);
                ChannelFuture channelFuture = ctx.channel().writeAndFlush(new TextWebSocketFrame(json));
                if(channelFuture.isSuccess()){
                    z.Log("发送信息|"+json);
                }else{
                    z.Error("发送消息失败|"+channelFuture.toString());
                }
            }else{
                z.Error("发送消息失败|z_messages无效");
            }
        }else{
            z.Error("发送消息失败|channel通道无效");
        }
    }

    /**
     * 发送消息
     * @param msg
     */
    private void SendMessages(z_messages msg) {
        if(z.isNotNull(msg) && z.isNotNull(msg.getTouserid())){

        }else{
            z.Error("发送消息失败|z_messages无效");
        }
    }

    /**
     * TextWebSocketFrame中提取Json转z_messages
     * @param msg
     * @return
     */
    private Result TextWebSocketFrameToZMessage(TextWebSocketFrame msg) {
        Result result = new Result();
        try {
            z_messages messages = JSONObject.parseObject(msg.text(), z_messages.class);
            if(z.isNotNull(messages)) {
                if(z.isNull(messages.getCommand_type())) {
                    result.setError("获取z_messages异常|通信命令不可为空");
                }
                if(z.isNull(z.code_detail.get("command_type_"+messages.getCommand_type()))){
                    result.setError("获取z_messages异常|通信命令无效:"+messages.getCommand_type());
                }
                if(z.isNotNull(messages.getMsgtype())) {
                    if(z.isNull(z.code_detail.get("msgtype_"+messages.getMsgtype()))) {
                        result.setError("获取z_messages异常|消息类型无效："+messages.getMsgtype());
                    }
                }
                //未发现错误，设置返回值
                if(!result.ifError()){
                    result.setSuccess(messages);
                }
            }else{
                result.setError("获取z_messages异常|msg：" + msg.text());
            }
        } catch (Exception e) {
            z.Error("获取z_messages异常|msg："+msg.text());
        }
        return result;
    }

    /**
     * 建立连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 添加连接
        System.out.println("Client connected: " + ctx.channel());
    }

    /**
     * 关闭连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 断开连接
        System.out.println("Client disconnected: " + ctx.channel());
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 异常处理
        cause.printStackTrace();
        ctx.close();
    }





}
